/**
 * 工具模块
 */

// 面包屑
export function gotBreads (menu, allMenuList) {
  var breadArr = [] // 面包屑数据
  breadArr.push(menu.menuName) // 最底层标签
  breadArr.push(menu.supMenuName) // 倒数第二层标签
  let SFCMenu = sessionStorage.getItem('SFCMenu')
  let isSFCMenu = false
  if (SFCMenu === '1') {
    isSFCMenu = true
  }
  if (menu.menuLevel === 3 && !isSFCMenu) {
    for (let i = 0; i < allMenuList.length; i++) {
      var fname = ''
      for (let j = 0; j < allMenuList[i].childNode.length; j++) {
        if (allMenuList[i].childNode[j].menuName === menu.supMenuName) {
          fname = allMenuList[i].childNode[j].supMenuName
          breadArr.push(fname)
          break
        }
      }
    }
  }
  // breadArr.push('首页')
  return breadArr.reverse()
}

// 获取url对应menu
export function getMenuByUrl (allMenuList, url) {
  var menu = {}
  for (let i = 0; i < allMenuList.length; i++) {
    if (allMenuList[i].childNode) { // 是否存在二级
      for (let j = 0; j < allMenuList[i].childNode.length; j++) {
        if (allMenuList[i].childNode[j].childNode) { // 是否存在三级
          for (let k = 0; k < allMenuList[i].childNode[j].childNode.length; k++) {
            let mUrl = allMenuList[i].childNode[j].childNode[k].menuUrl
            if (mUrl.indexOf('?') > -1) {
              let index = mUrl.indexOf('?')
              mUrl = mUrl.substring(0, index)
            }
            if (mUrl === url) {
              menu = allMenuList[i].childNode[j].childNode[k]
              break
            }
          }
        } else {
          let mUrl = allMenuList[i].childNode[j].menuUrl
          if (mUrl.indexOf('?') > -1) {
            let index = mUrl.indexOf('?')
            mUrl = mUrl.substring(0, index)
          }
          if (mUrl === url) {
            menu = allMenuList[i].childNode[j]
            break
          }
        }
      }
    } else {
      if (allMenuList[i].menuUrl === url) {
        menu = allMenuList[i]
        break
      }
    }
  }
  return menu
}

/**
 * 自动调整iframe高度
 * 适用于初始菜单加载页面
 * 增加Firefox浏览器处理
 * 企业管理页面专用
 */
export function autoHeight () {
  var browserInfo = window.navigator.userAgent
  setTimeout(function () {
    var iframe = parent.document.getElementById('loader')
    var iframeWin = iframe.contentWindow
    if (iframeWin.document.body) {
      var h1 = iframeWin.document.documentElement.scrollHeight
      var h2 = iframeWin.document.body.scrollHeight
      console.log('h1:' + h1 + '--h2:' + h2)
      var hmax = Math.max(h1, h2)
      var hmin = Math.min(h1, h2)
      var iframeH = 0
      if (browserInfo.indexOf('Firefox') >= 0) {
        iframeH = hmin
      } else {
        iframeH = hmax
      }
      iframe.height = iframeH
      console.log(iframeH)
    }
  }, 600)
}

/**
 * 根据限定高度自动调整iframe高度
 * 适用于带有伸缩框页面
 * @param limits 限制高度阀值
 */
export function autoHeightBylimit (limits) {
  var iframe = parent.document.getElementById('loader')
  var iframeWin = iframe.contentWindow
  if (iframeWin.document.body) {
    var h1 = iframeWin.document.documentElement.scrollHeight
    var h2 = iframeWin.document.body.scrollHeight
    var Hmin = Math.min(h1, h2)
    var Hmax = Math.max(h1, h2)
    console.log('Hmin:' + Hmin + '--Hmax:' + Hmax)
    var hh = 0 // iframe设置高度
    if (Hmin > limits) {
      hh = Hmax
    } else {
      hh = Hmin
    }
    iframe.height = hh
    console.log(hh)
  }
}

/**
 * 自动调整iframe高度
 * 适用于初始菜单加载页面
 * 不针对Firefox浏览器判断
 * 取最大值
 */
export function autoHeight2 () {
  setTimeout(function () {
    var iframe = parent.document.getElementById('loader')
    var iframeWin = iframe.contentWindow
    if (iframeWin.document.body) {
      var h1 = iframeWin.document.documentElement.scrollHeight
      var h2 = iframeWin.document.body.scrollHeight
      console.log('h1:' + h1 + '--h2:' + h2)
      var hmax = Math.max(h1, h2)
      var iframeH = hmax
      iframe.height = iframeH
      console.log(iframeH)
    }
  }, 600)
}

/**
 * 自动调整iframe高度
 * 适用于初始菜单加载页面
 * 不针对Firefox浏览器判断
 * 取最小值
 */
export function autoHeight3 () {
  setTimeout(function () {
    var iframe = parent.document.getElementById('loader')
    var iframeWin = iframe.contentWindow
    if (iframeWin.document.body) {
      var h1 = iframeWin.document.documentElement.scrollHeight
      var h2 = iframeWin.document.body.scrollHeight
      console.log('h1:' + h1 + '--h2:' + h2)
      var hmin = Math.min(h1, h2)
      var iframeH = hmin
      iframe.height = iframeH
      console.log(iframeH)
    }
  }, 600)
}

/**
 * 获取按钮权限
 * @param index 按钮id下标
 * @param companytype 账户所属公司类型
 * @param adminButtons 运营权限按钮id集合
 * @param ebookingButtons 供应权限按钮id集合
 * @param mdButtons 门店权限按钮id集合
 */
export function buttonAuth (index, companytype, adminButtons, ebookingButtons, mdButtons) {
  let buttonIds = sessionStorage.getItem('buttonIds')
  if (buttonIds === null) {
    return false
  }
  let baseButtons = []
  if (companytype === 0) { // 运营
    baseButtons = adminButtons
  } else if (companytype === 1) { // 零售商
    baseButtons = ebookingButtons
  } else if (companytype === 2) { // 代理商
    baseButtons = mdButtons
  }
  if (!baseButtons || !baseButtons.length) return true // 如果权限按钮id集合是空，则代表不限制--田珂铭--2017年9月11日 10:40:58
  let id = baseButtons[index]
  if (!id) return true // 如果按钮权限id在集合里找不到，则代表不限制--田珂铭--2017年9月11日 10:40:48
  buttonIds = ',' + buttonIds + ','
  if (buttonIds.indexOf(',' + id + ',') >= 0) {
    return true
  } else {
    return false
  }
}

/**
 * 菜单数组排序--根据menuTop从小到大排序
 * @param menus 菜单数组
 */
export function sortByMenuTop (menus) {
  if (menus.length) {
    menus.sort(function (a, b) {
      return a.menuTop - b.menuTop
    })
    for (let i = 0; i < menus.length; i++) {
      if (menus[i].childNode && menus[i].childNode.length) {
        sortByMenuTop(menus[i].childNode)
      }
    }
  }
}
/**
 * 人机验证动态加载 【luosimao】
 *
 */
export function initLSM (_this) {
  var oldLSM = document.getElementsByClassName('luosimao')
  _this(oldLSM).remove()
  var c = document.createElement('script')
  c.type = 'text/javascript'
  c.async = true
  c.className = 'luosimao'
  c.src = (document.location.protocol === 'https:' ? 'https://' : 'http://') + 'captcha.luosimao.com/static/dist/captcha.js?v=' + new Date().getTime()
  var s = document.getElementsByTagName('script')[0]
  s.parentNode.insertBefore(c, s)
}

/**
 * URL中获取参数值--lx--2017-4-20 11:18:40
 */
let getUrlParam = function (name) {
  if (name !== null || name !== '') {
    var reg = new RegExp('(^|\\?|&)' + name + '=([^&]*)(\\s|&|$)', 'i')
    if (reg.test(location.href)) {
      return unescape(RegExp.$2.replace(/\+/g, ''))
    } else {
      return ''
    }
  }
}

/**
 * 浏览器历史前进或后退时，重设面包屑
 */
export function resetBreads (that) {
  try {
    var currPath = window.location.pathname
    if (window.location.search && currPath === '/baseCompanyEdit' && getUrlParam('type') === 'maintenance') currPath += window.location.search // 有的菜单中的地址带有查询参数(如果是 公司维护。。。)
    var menuUrl = that.$store.state.locationpath // sessionStorage.getItem('menuUrl')
    var u = sessionStorage.getItem('user')
    var uObj = JSON.parse(u)
    if (currPath !== menuUrl) {
      /**
       * 门店搜索处理
       */
      if (currPath.lastIndexOf('/') > 0) {
        currPath = '/' + currPath.split('/')[1]
      }
      if (uObj.type === 0 && currPath === '/baseHelpList') { // 帮助中心
        let breads = ['首页', '帮助中心']
        that.$store.dispatch('updateBreads', breads)
        that.$store.dispatch('updatelocationpath', currPath)
        that.$store.dispatch('showActive', {url: currPath})
        sessionStorage.setItem('breads', breads)
        sessionStorage.setItem('menuUrl', currPath)
        return
      } else if (uObj.type === 0 && currPath === '/baseFeedback') { // 问题反馈
        let breads = ['首页', '问题反馈']
        that.$store.dispatch('updateBreads', breads)
        that.$store.dispatch('updatelocationpath', currPath)
        that.$store.dispatch('showActive', {url: currPath})
        sessionStorage.setItem('breads', breads)
        sessionStorage.setItem('menuUrl', currPath)
        return
      } else if (uObj.type === 2 && currPath === '/survey') { // 问题反馈
        let breads = ['首页', '默认', '概况']
        that.$store.dispatch('updateBreads', breads)
        that.$store.dispatch('updatelocationpath', currPath)
        that.$store.dispatch('showActive', {url: currPath})
        sessionStorage.setItem('breads', breads)
        sessionStorage.setItem('menuUrl', currPath)
        return
      } else if (uObj.type === 0 && currPath === '/baseCompanyEdit') { // 公司管理
        let queryType = getUrlParam('type')
        let jsnBreads = {
          add: ['首页', '默认', '商家管理', '商家管理', '新增'],
          edit: ['首页', '默认', '商家管理', '商家管理', '编辑'],
          detail: ['首页', '默认', '商家管理', '商家管理', '详情'],
          verify: ['首页', '默认', '商家管理', '商家管理', '审核']
        }
        that.$store.dispatch('updateBreads', jsnBreads[queryType])
        that.$store.dispatch('updatelocationpath', currPath)
        that.$store.dispatch('showActive', {url: currPath})
        sessionStorage.setItem('breads', jsnBreads[queryType])
        sessionStorage.setItem('menuUrl', currPath)
        return
      } else if (uObj.type === 0 && currPath === '/baseAccount' && getUrlParam('companyName')) { // 如果是运营的员工账号管理
        let queryCompanyName = getUrlParam('companyName')
        let breads = ['首页', '商家管理', '商家管理', '员工账号', queryCompanyName]
        that.$store.dispatch('updateBreads', breads)
        that.$store.dispatch('updatelocationpath', currPath)
        that.$store.dispatch('showActive', {url: currPath})
        sessionStorage.setItem('breads', breads)
        sessionStorage.setItem('menuUrl', currPath)
        return
      } else if (uObj.type === 1 && currPath === '/storeMessageAdd') { // 门店新增编辑（商家）
        let queryType = getUrlParam('ftype')
        let jsnBreads = {
          add: ['首页', '应用管理', '门店管理', '新增'],
          edit: ['首页', '应用管理', '门店管理', '编辑']
        }
        that.$store.dispatch('updateBreads', jsnBreads[queryType])
        that.$store.dispatch('updatelocationpath', currPath)
        that.$store.dispatch('showActive', {url: currPath})
        sessionStorage.setItem('breads', jsnBreads[queryType])
        sessionStorage.setItem('menuUrl', currPath)
        return
      } else if (uObj.type === 1 && currPath === '/retailGoodsGroup') { // 商家
        let breads = ['首页', '商品管理', '商品分组']
        that.$store.dispatch('updateBreads', breads)
        that.$store.dispatch('updatelocationpath', currPath)
        that.$store.dispatch('showActive', {url: currPath})
        sessionStorage.setItem('breads', breads)
        sessionStorage.setItem('menuUrl', currPath)
        return
      } else if (uObj.type === 0 && currPath === '/storeMessageAdd') { // 门店新增编辑（运营）
        let queryType = getUrlParam('ftype')
        let jsnBreads = {
          add: ['首页', '商家管理', '门店管理', '新增'],
          edit: ['首页', '商家管理', '门店管理', '编辑']
        }
        that.$store.dispatch('updateBreads', jsnBreads[queryType])
        that.$store.dispatch('updatelocationpath', currPath)
        that.$store.dispatch('showActive', {url: currPath})
        sessionStorage.setItem('breads', jsnBreads[queryType])
        sessionStorage.setItem('menuUrl', currPath)
        return
      } else if (currPath === '/retailGoodsAdd') { // 订单详情新增编辑
        let queryType = getUrlParam('ftype')
        let jsnBreads = {
          add: ['首页', '商品管理', '商品管理', '发布商品'],
          edit: ['首页', '商品管理', '商品管理', '编辑商品']
        }
        that.$store.dispatch('updateBreads', jsnBreads[queryType])
        that.$store.dispatch('updatelocationpath', currPath)
        that.$store.dispatch('showActive', {url: currPath})
        sessionStorage.setItem('breads', jsnBreads[queryType])
        sessionStorage.setItem('menuUrl', currPath)
        return
      } else if (currPath === '/baseGoodsDetails') { // 如果是订单详情
        let queryType = 'detail' // getUrlParam('ftype')
        let jsnBreads = {
          detail: ['首页', '订单管理', '零售订单', '详情'],
          edit: ['首页', '订单管理', '零售订单', '编辑']
        }
        that.$store.dispatch('updateBreads', jsnBreads[queryType])
        that.$store.dispatch('updatelocationpath', currPath)
        that.$store.dispatch('showActive', {url: currPath})
        sessionStorage.setItem('breads', jsnBreads[queryType])
        sessionStorage.setItem('menuUrl', currPath)
        return
      } else if (currPath === '/retailOrderRefundDetails') { // 如果是查看退款订单--add by cb in 2017-09-25
        let queryType = 'detail' // getUrlParam('ftype')
        var list = sessionStorage.getItem('breads').split(',')
        let jsnBreads = {
          detail: [list[0], list[1], list[2], '退款订单详情']
        }
        that.$store.dispatch('updateBreads', jsnBreads[queryType])
        that.$store.dispatch('updatelocationpath', currPath)
        that.$store.dispatch('showActive', {url: currPath})
        sessionStorage.setItem('breads', jsnBreads[queryType])
        sessionStorage.setItem('menuUrl', currPath)
        return
      }
      // 企业信息维护特殊处理
      // if (currPath === '/baseCompanyEdit' && uObj.type !== 0) {
      //   currPath = '/maintenanceCompany'
      // }
      let allMenus = sessionStorage.getItem('allMenus')
      let menuList = JSON.parse(allMenus)
      if (menuList && menuList.length) {
        let menu = getMenuByUrl(menuList, currPath)
        if (menu) {
          let breads = gotBreads(menu, menuList)
          that.$store.dispatch('updateBreads', breads)
          that.$store.dispatch('updatelocationpath', currPath)
          that.$store.dispatch('showActive', {url: currPath})
          // 更新sessionStorage
          sessionStorage.setItem('breads', breads)
          sessionStorage.setItem('menuUrl', currPath)
        }
      }
    }
  } catch (error) {
    console.log(error)
  }
}
/**
 * 验证密码至少两种字符
 *
 */
export function passwordLevel (password) {
  var Modes = 0
  for (var i = 0; i < password.length; i++) {
    Modes |= CharMode(password.charCodeAt(i))
  }
  return bitTotal(Modes)
  // CharMode函数
  function CharMode (iN) {
    if (iN >= 48 && iN <= 57) { // 数字
      return 1
    }
    if (iN >= 65 && iN <= 90) { // 大写字母
      return 2
    }
    if ((iN >= 97 && iN <= 122) || (iN >= 65 && iN <= 90)) {
      // 大小写
      return 4
    } else {
      return 8 // 特殊字符
    }
  }

  // bitTotal函数
  function bitTotal (num) {
    var modes = 0
    for (var i = 0; i < 4; i++) {
      if (num & 1) modes++
      num >>>= 1
    }
    return modes
  }
}
/**
 * 获取路径的参数
 * 禹光彩
 * 2017-7-19 17:18:25
 */
export function getUrlParam3 (name) { // 获取参数
  if (name !== null || name !== '') {
    let reg = new RegExp('(^|\\?|&)' + name + '=([^&]*)(\\s|&|$)', 'i')
    if (reg.test(window.location.href)) {
      return decodeURI(RegExp.$2.replace(/\+/g, ' '))
    }
    return ''
  }
}
/**
 * session超时处理
 * 禹光彩
 * 2017-8-2 14:43:23
 */
export function sessionOut (_this) {
  let num = _this.$store.state.timeOut
  if (num === 0) {
    _this.$store.dispatch('timeOut', 1)
    sessionStorage.clear()
    _this.$alert('登录超时，请重新登录', ' ', {
      type: 'warning'
    }).then(() => {
      _this.$router.push({path: '/login'})
    })
  }
}
// value 格式为13位unix时间戳
// 10位unix时间戳可通过value*1000转换为13位格式
export function formatDate (date, fmt) {
  if (date === '' || date === undefined || date.getFullYear() === 1900) {
    return ''
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}
function padLeftZero (str) {
  return ('00' + str).substr(str.length)
}

/**
 * 串行化json对象为字符串
 * @author 田珂铭
 * @since 2017年9月25日 09:52:10
 * @param jo
 * @returns {string}
 */
export function serialize (jo) {
  let queryString = ''
  for (let key in jo) {
    queryString += '&' + key + '=' + jo[key]
  }
  return queryString.substring(1)
}
/**
 * 时间格式转换字符串
 * 禹光彩
 * 2017-11-24 14:20:14
 */
export function dateStr (time) {
  var d = new Date(time)
  var year = d.getFullYear()
  var month = ((d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1))
  var date = (d.getDate() < 10 ? '0' + d.getDate() : d.getDate())
  var hour = (d.getHours() < 10 ? '0' + d.getHours() : d.getHours())
  var minute = (d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes())
  var second = (d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds())
  return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
}

/**
 * 上传时初始化fileList(将字址转符串换为地址数组)
 * @author 田珂铭
 * @since 2017年11月26日 23:26:14
 * @param fp
 * @returns {Array}
 */
export function initFileList (fp, prefix) {
  let arr = str2Arr(fp, '\\|')
  let pl = []
  for (let i = 0; i < arr.length; i++) {
    pl.push({name: arr[i].substring(arr[i].lastIndexOf('/') + 1), url: prefix + arr[i], status: 'success'})
  }
  return pl
}

/**
 * 字符串转数组
 * @author 田珂铭
 * @since 2017年11月26日 23:26:14
 * @param str
 * @param separator
 * @returns {*}
 */
export function str2Arr (str, separator) {
  if (!str) return []
  let reg = new RegExp(separator)
  let arr = str.split(reg)
  return arr
}
